package com.crazy.mybatis.gerenator.service.xml;

import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Component;

import com.crazy.mybatis.gerenator.service.Context;
import com.crazy.mybatis.gerenator.service.common.ElementName;

@Component
public class ResultMapBuilder extends AbstractElementBuilder implements ElementBuilder {

	static final String DEFAULT_ID = "BaseResultMap";
	
	public ResultMapBuilder() {
		this(DEFAULT_ID, ElementName.RESULT_MAP);
	}
	
	public ResultMapBuilder(String id, String elementName) {
		super(id, elementName);
	}

	@Override
	public Element build(Context context) {
		Element resultMap = DocumentHelper.createElement(this.elementName);
		resultMap.addAttribute("id", this.id);
		resultMap.addAttribute("type", context.getAbsoluteModel());
		for (String column : context.getColumnList()) {
			Element result;
			if (!column.equals(context.getPrimaryKey())) {
				result = resultMap.addElement("result");
			} else {
				result = resultMap.addElement("id");
			}
			result.addAttribute("column", column);
			result.addAttribute("property", context.getColumnPropertyMap().get(column));
			result.addAttribute("jdbcType", context.getColumnJdbcTypeMap().get(column));
		}
		return resultMap;
	}

}
